﻿namespace Vibstudio.NetConfigurator.IoC
{
    #region Namespaces

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    using Vibstudio.NetConfigurator.Common;
    using Vibstudio.NetConfigurator.IoC.Configuration;

    #endregion

    public static class Container
    {
        public static Dictionary<string, T> Resolve<T>() where T : IAggregateRoot
        {
            string sectionName = null;

            if (typeof(T).Name == "IConfiguration") sectionName = "NcConfiguration";
            if (typeof(T).Name == "IComposition") sectionName = "NcComposition";
            if (typeof(T).Name == "IValidation") sectionName = "NcValidation";

            NcConfiguration config = NcConfiguration.GetConfig(sectionName);

            return config.NcSettings
                         .Cast<NcSettingElement>()
                         .ToDictionary(element => element.Key,
                                       element => CreateInstance<T>(element.MapTo));
        }

        private static T CreateInstance<T>(string mapTo) where T : IAggregateRoot
        {
            try
            {
                string typeName = mapTo.Split(',').First();
                string assmblyName = mapTo.Split(',').Last().TrimStart();
                string assemblyFile = String.Format("{0}.dll", Path.Combine(Directory.GetCurrentDirectory(), assmblyName));

                Assembly assembly = Assembly.LoadFrom(assemblyFile);

                return (T) assembly.CreateInstance(typeName, ignoreCase: true);
            }
            catch (Exception)
            {
                return default(T);
            }
        }
    }
}
